let testId = '';

window.addEventListener('DOMContentLoaded', () => {
  isStuLogin();
});

function loadPage() {
  loadSubjects();
}

function loadSubjects() {
  testId = localStorage.getItem('testId');
  $.get(`${app.urlLocation.querySubjectByTestId}`, {testId: testId}, res => {
    let subject = res[0];
    $('.paper-title').text(subject.testTitle);
    $('.paper-class-type').text(subject.classType);
    countDown(subject.testTime);
    let subjectHtml = '';
    $.each(res, (i, v) => {
      subjectHtml += writeTestCard(v, i);
    });
  })
}

function writeTestCard(subject, length) {
  let subjectType = subject.subjectType;
  let subjectHtml = '';
  switch (subjectType) {
    case 1:
      subjectHtml += returnOptionHeader(subject);
      let subjectContent = subject.subjectContent.split('|');
      $.each(subjectContent, (i, v) => {
        subjectHtml += returnSingleOptionHtml(v, length, i);
      });
      subjectHtml += `</div></div>`;
      break;
    case 2:
      subjectHtml += returnOptionHeader(subject);
      let multiSubjectContent = subject.subjectContent.split('|');
      $.each(multiSubjectContent, (i, v) => {
        subjectHtml += returnMultiOptionHtml(v, length, i);
      });
      subjectHtml += `</div></div>`;
      break;
    case 3:
      subjectHtml += returnOptionHeader(subject);
      subjectHtml += returnOpenHtml(subject.subjectContent, length);
      subjectHtml += `</div></div>`;
      break;
  }
  $('.test-content').append(subjectHtml);
  app.resetForm();
}

function returnOptionHeader(subject) {
  return `<div class="layui-card"><span class="subject-id layui-hide">${subject.subjectId}</span>` +
    `<div class="layui-card-header">` +
    `<span class="layui-form-label">第<span class="question-no">${subject.testNo}</span>题</span>` +
    `<span class="question-content">${subject.subjectTitle}</span>` +
    `<span class="question-scale">(分值：${subject.singleScale} 分)</span>` +
    `<span class="question-type layui-hide layui-clear">${subject.subjectType}</span></div>` +
    `<div class="layui-card-body">`;
}

function returnSingleOptionHtml(subject, length, index) {
  let optionPre = String.fromCharCode(65 + index);
  return `<div class="layui-input-block">` +
    `<input type="radio" name="answer${length}" value="${index + 1}" title="">` +
    `<span class="option">${optionPre}.&nbsp;&nbsp;${subject}</span></div>`;
}

function returnMultiOptionHtml(subject, length, index) {
  let optionPre = String.fromCharCode(65 + index);
  return `<div class="layui-input-block">` +
    `<input type="checkbox" name="answer${length}" value="${index + 1}" title="" lay-skin="primary">` +
    `<span class="option">${optionPre}.&nbsp;&nbsp;${subject}</span>` +
    `</div>`;
}

function returnOpenHtml(subject, length) {
  return `<div class="layui-input-block">` +
    `<textarea name="answer${length}" placeholder="请输入答案" class="layui-textarea" title=""></textarea>` +
    `</div>`;
}

$('#create').click(() => {
  submit(true);
});

/* 提交答案 */

function submit(flag) {
  let layuiCard = $('.layui-card');
  let apBank = [];
  for (let i = 0; i < layuiCard.length; i++) {
    let curLayuiCard = layuiCard.eq(i);
    let subjectType = curLayuiCard.find('span.layui-clear').text(); // 获取当前题目类型
    let subjectId = curLayuiCard.find('.subject-id').text(); // 获取当前题目的编号
    let stuId = $('.layui-nav img').attr('alt'); // 获取当前登录账户的 id
    let subjectNo = i + 1; // 获取当前题目的题号
    let subjectAnswer = ''; // 获取当前题目的答案，先定义好变量，后面获取
    let singleAp = {};
    switch (subjectType) {
      case '1':
        let radioed = curLayuiCard.find('.layui-form-radioed');
        if (flag) {
          if (radioed.length === 0) {
            app.alertInfo(`第${i + 1}题还未做，不能提交`);
            return;
          }
          // 获取选中的答案的数值
          subjectAnswer = radioed.prev('input').val();
        } else {
          subjectAnswer = '0';
        }
        break;
      case '2':
        let checked = curLayuiCard.find('.layui-form-checked');
        if (flag) {
          if (checked.length === 0) {
            app.alertInfo(`第${i + 1}题还未做，不能提交`);
            return;
          }
          // 获取选中的答案的数值
          subjectAnswer = [];
          for (let j = 0; j < checked.length; j++) {
            subjectAnswer.push(checked.eq(j).prev('input').val());
          }
          subjectAnswer = subjectAnswer.join('|');
        } else {
          subjectAnswer = '0';
        }
        break;
      case '3':
        subjectAnswer = curLayuiCard.find('textarea').val();
        if (flag) {
          if (subjectAnswer.trim() === '') {
            app.alertInfo(`第${i + 1}题还未做，不能提交`);
            return;
          }
        } else {
          subjectAnswer = '0';
        }
        break;
    }
    singleAp.stuId = stuId;
    singleAp.testId = testId;
    singleAp.subjectNo = subjectNo;
    singleAp.answerSubject = subjectId;
    singleAp.subjectAnswer = subjectAnswer;
    apBank.push(singleAp);
  }
  apBank = JSON.stringify(apBank);
  $.post(`${app.urlLocation.addAp}`, {apString: apBank}, res => {
    if (res === 200) {
      app.alertInfo('答案提交成功，正在进行跳转');
      setTimeout(() => {
        window.location.href = '/student-action/index';
      }, 1000);
    } else {
      app.alertInfo('答案提交失败，请重试或联系管理员');
    }
  })
}

/* 考试时间倒计时计数器 */

function countDown(time) {
  let date;
  let second = 59;
  time -= 1;
  date = time + ':' + second;
  second -= 1;
  $('.times').html(date);
  let timeInterval = setInterval(function () {
    date = time + ':' + second;
    if (second === 0) {
      if (time === 0) {
        clearInterval(timeInterval);
        submit(false);
      }
      time -= 1;
      second = 60;
    }
    $('.times').html(date);
    second -= 1;
  }, 1000);
}

/* 结束 */

/* 离开页面视为放弃考试，自动提交试卷答案 */

document.addEventListener('visibilitychange', function () {
  if (document.hidden) {
    // 浏览器提交时间长会出现多次提交的情况，所以拉到
    //submit(false);
  }
});

/* 结束 */